/**
 * 华为云API签名工具 - 直接使用官方signer.js
 * 确保与华为云官方SDK完全一致
 */

// 全局变量存储签名器模块
let signerModule: any = null

// 初始化签名器模块
async function initSignerModule() {
  if (!signerModule) {
    // @ts-ignore
    signerModule = await import('../assets/signer/signer.js')
  }
  return signerModule
}

/**
 * HTTP请求类 - 直接使用官方实现
 */
export class HttpRequest {
  method: string
  host: string
  uri: string
  query: Record<string, any>
  headers: Record<string, string>
  body: string

  constructor(method: string = '', url: string = '', headers: Record<string, string> = {}, body: string = '') {
    // 解析URL
    const urlObj = new URL(url)

    this.method = method
    this.host = urlObj.host
    this.uri = urlObj.pathname + urlObj.search
    this.query = {}
    this.headers = { ...headers }
    this.body = body

    // 解析查询参数
    urlObj.searchParams.forEach((value, key) => {
      this.query[key] = value
    })
  }
}

/**
 * 华为云签名器 - 直接使用官方实现
 */
export class BrowserSigner {
  private officialSigner: any
  private initialized: boolean = false

  constructor(private accessKey: string = '', private secretKey: string = '') {
    // 构造函数中不执行异步操作
  }

  /**
   * 异步初始化签名器
   */
  private async init(): Promise<void> {
    if (!this.initialized) {
      const module = await initSignerModule()
      const { Signer: OfficialSigner } = module
      this.officialSigner = new OfficialSigner()
      this.officialSigner.Key = this.accessKey
      this.officialSigner.Secret = this.secretKey
      this.initialized = true
    }
  }

  /**
   * 设置访问密钥
   */
  async setCredentials(accessKey: string, secretKey: string): Promise<void> {
    await this.init()
    this.accessKey = accessKey
    this.secretKey = secretKey
    this.officialSigner.Key = accessKey
    this.officialSigner.Secret = secretKey
  }

  /**
   * 对HTTP请求进行签名 - 直接使用官方Sign方法
   */
  async Sign(request: HttpRequest): Promise<{
    hostname: string
    path: string
    method: string
    headers: Record<string, string>
  }> {
    await this.init()

    // 创建官方HttpRequest对象
    const module = await initSignerModule()
    const { HttpRequest: OfficialHttpRequest } = module
    const officialRequest = new OfficialHttpRequest(
      request.method,
      `https://${request.host}${request.uri}`,
      request.headers,
      request.body
    )

    // 使用官方签名方法
    return this.officialSigner.Sign(officialRequest)
  }

  /**
   * 兼容旧接口
   */
  async sign(request: HttpRequest): Promise<{
    hostname: string
    path: string
    method: string
    headers: Record<string, string>
  }> {
    return await this.Sign(request)
  }
}

/**
 * 创建签名器实例
 */
export function createSigner(accessKey?: string, secretKey?: string): BrowserSigner {
  return new BrowserSigner(accessKey, secretKey)
}
